use std::io::Cursor;

use image::{DynamicImage, ImageError, ImageFormat};
use wasm_bindgen::prelude::*;

fn image_format(img_fmt: String) -> Result<ImageFormat, JsValue> {
    match img_fmt.to_lowercase().as_str() {
        "jpg" | "jpeg" => Ok(ImageFormat::Jpeg),
        "png" => Ok(ImageFormat::Png),
        "gif" => Ok(ImageFormat::Gif),
        "bmp" => Ok(ImageFormat::Bmp),
        "tiff" | "tif" => Ok(ImageFormat::Tiff),
        "webp" => Ok(ImageFormat::WebP),
        _ => Err(JsValue::from_str(&format!(
            "unsupported image minetype: {:?}",
            img_fmt
        ))),
    }
}

#[wasm_bindgen]
pub fn convert(
    image: &[u8],
    convert_type: String,
    // quality: Option<f32>, not used yet
) -> Result<Vec<u8>, JsValue> {
    // let _q = quality.unwrap_or(75.0);
    let convert_type: ImageFormat = image_format(convert_type)?;

    let img: DynamicImage = image::load_from_memory(image)
        .map_err(|e: ImageError| JsValue::from_str(&format!("unsupported image type: {:?}", e)))?;

    let encoded: Vec<u8> = Vec::new();
    let mut cursor: Cursor<Vec<u8>> = Cursor::new(encoded);
    img.write_to(&mut cursor, convert_type)
        .map_err(|e: ImageError| JsValue::from_str(&format!("failed to write image: {:?}", e)))?;

    // 返回 WebP 数据
    Ok(cursor.into_inner())
}
